<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '800px' }"
    :title="title"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
    :mask-closable="false"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :label-width="120" :rules="rules">
      <n-form-item label="员工姓名：" path="accountName">
        <n-input v-model:value="form.accountName" style="width: 400px" />
      </n-form-item>
      <n-form-item label="所属部门：" path="departmentId">
        <n-tree-select
          v-model:value="form.departmentId"
          style="width: 400px"
          :options="departmentList"
          key-field="id"
          label-field="departmentName"
          clearable
        />
      </n-form-item>
      <n-form-item label="登录邮箱：" path="accountMailbox">
        <n-input v-model:value="form.accountMailbox" style="width: 400px" />
      </n-form-item>
      <n-form-item label="登录密码：" path="password">
        <n-input
          v-model:value="form.password"
          type="password"
          style="width: 400px; margin-right: 10px"
          placeholder="长度至少6位，且至少包含字母和数字两种字符"
        />
        <n-text v-if="getProps.modalData.type === 'edit'">未填写新密码，则保存原来的密码</n-text>
      </n-form-item>
      <n-form-item label="确认密码：" path="password1">
        <n-input v-model:value="form.password1" type="password" style="width: 400px" placeholder="请输入相同密码" />
      </n-form-item>
      <n-form-item label="员工岗位" path="roleIdList">
        <n-select
          v-model:value="form.roleIdList"
          style="width: 400px"
          placeholder="请选择员工岗位"
          :options="roleIdList"
          multiple
          value-field="id"
          label-field="roleName"
          clearable
        />
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" :loading="loading" @click="handleSave">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
  import {
    NModal,
    NForm,
    NFormItem,
    NSelect,
    NInput,
    NSpace,
    NButton,
    FormValidationError,
    NText,
    NTreeSelect
  } from 'naive-ui'
  import { useStore } from '@/store'
  import { onMounted, reactive, ref } from 'vue'
  const store = useStore()
  const emits = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })

  const getProps = reactive(props)
  const loading = ref(false)
  const loadingDetail = ref(false)
  const formRef = ref(null)
  const form = ref({
    accountName: null,
    departmentId: null,
    accountMailbox: null,
    password: null,
    password1: null,
    roleIdList: null,
    accountId: null
  })
  const roleIdList = ref([])

  const rules = reactive({
    accountName: { type: 'string', required: true, message: '请输入员工姓名', trigger: 'blur' },
    departmentId: { type: 'number', required: true, message: '请选择所属部门', trigger: 'blur' },
    accountMailbox: { type: 'email', required: true, message: '请输入登录邮箱', trigger: 'blur' },
    password: {
      type: 'string',
      required: getProps.modalData.type !== 'edit' ? true : false,
      trigger: 'blur',
      validator(rule: any, value: number) {
        const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/
        if (regex.test(String(value)) || getProps.modalData.type === 'edit') {
          return true
        } else {
          return new Error('密码必须包含6位及以上中英文')
        }
      }
    },
    password1: {
      type: 'string',
      required: getProps.modalData.type !== 'edit' ? true : false,
      message: '两次输入密码不一致',
      trigger: 'blur',
      validator: (rule: any, value: null) => {
        if (value !== form.value.password) {
          return new Error('两次输入密码不一致', value, form.value.password)
        }
        return true
      }
    },
    roleIdList: { type: 'array', required: true, message: '请选择', trigger: 'change' }
  })
  const title = '基本信息'
  const departmentList = ref([])
  onMounted(() => {
    getDepartmentList()
    getRoleIdList()
    if (props.modalData.type === 'edit') {
      getDetail()
    }
  })
  onMounted(() => {
    getDepartmentList()
  })

  const getDepartmentList = async () => {
    const { data } = await store.dispatch('system/departmentList')
    departmentList.value = [data]
  }

  async function getRoleIdList() {
    loadingDetail.value = true
    const { data } = await store.dispatch('system/roleList')
    roleIdList.value = data
  }

  async function getDetail() {
    form.value = getProps.modalData.row
  }

  function handleClose() {
    getProps.modalData.show = false
  }

  function handleSave() {
    formRef.value?.validate(async (errors: Array<FormValidationError>) => {
      if (!errors) {
        await submitData()
      } else {
        console.log(errors)
      }
    })
  }

  async function submitData() {
    loading.value = true
    const { data } = await store
      .dispatch('system/operatorSave', {
        ...form.value,
        accountId: props.modalData.row.accountId
      })
      .finally(() => {
        loading.value = false
      })
    emits('success', data)
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss"></style>
